/*
 * @lc app=leetcode.cn id=85 lang=c
 *
 * [85] 最大矩形
 */

// @lc code=start


int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize){
    int m = matrixSize;
    if (m == 0) {
        return 0;
    }   
    int n = matrixColSize[0];
    int left[m][n];
    memset(left, 0, sizeof(left));
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (matrix[i][j] == '1') {
                left[i][j] = (j == 0 ? 1 : left[i][j - 1] + 1);
            } 
        }
    }
    //printf("%d", left[0][0]);
    int ret = 0;
    for (int j = 0; j < n; ++j) {
        int up[m], down[m];
        memset(up, 0, sizeof(up));
        memset(down, 0, sizeof(down));
        int stk[m];
        int top = 0;
        for (int i = 0; i < m; ++i) {
            while (top > 0 && left[stk[top - 1]][j] >= left[i][j]) {
                top--;
            }
            up[i] = top == 0 ? -1 : stk[top - 1];
            stk[top++] = i;
        }

        top = 0;
        for (int i = m - 1; i >= 0; --i) {
            while (top > 0 && left[stk[top - 1]][j] >= left[i][j]) {
                top--;
            }
            down[i] = top == 0 ? m : stk[top - 1];
            stk[top++] = i;
        }

        for (int i = 0; i < m; ++i) {
            int height = down[i] - up[i] - 1;
            int area = height * left[i][j];
            ret = fmax(ret, area);
        }
    }
    return ret;
}
// @lc code=end

